<template>
  <o-modal
    v-model="visible"
    :title="$srv.getI18nBySrv((configData && configData.modalTitle) || '')"
    :size="modalSize"
    :mask="true"
    :tap-close="false"
    :show-footer="true"
    v-if="configData && configData.modalTitle"
  >
    <!-- @on-close="handleCancel" -->
    <div slot="content" class="paint-guide-container" v-if="configData">
      <!-- 零件基本信息 -->
      <div
        class="part-info"
        v-if="configData.partInfoFields && configData.partInfoFields.length"
      >
        <div
          v-for="(field, index) in configData.partInfoFields"
          :key="index"
          class="info-item"
        >
          <span class="label"
            >{{ $srv.getI18nBySrv((field && field.label) || '') }}:</span
          >
          <span class="value">{{
            $srv.getI18nBySrv(partInfo[(field && field.dataKey) || ''] || '')
          }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div
        class="action-buttons"
        v-if="configData.buttons && configData.buttons.length"
      >
        <Button
          v-for="(button, index) in configData.buttons"
          :key="index"
          :type="(button && button.type) || 'default'"
          @click="handleButtonClick((button && button.text) || '')"
          :disabled="button && button.text === 'delete' && !selectedRows.length"
        >
          {{ $srv.getI18nBySrv((button && button.text) || '') }}
        </Button>
      </div>

      <!-- 提示消息 -->
      <div class="tips" v-if="configData.tips">
        <Icon :type="(configData.tips && configData.tips.icon) || ''" />
        <span
          >{{
            $srv.getI18nBySrv((configData.tips && configData.tips.text) || '')
          }}：</span
        >
        <span>{{
          $srv.getI18nBySrv((configData.tips && configData.tips.content) || '')
        }}</span>
      </div>

      <!-- 喷漆编码表格 -->
      <vxe-table
        ref="paintTable"
        :data="tableData"
        border
        show-overflow
        :height="tableHeight"
        @checkbox-change="selectChangeEvent"
        v-if="
          configData.tableConfig &&
            configData.tableConfig.columns &&
            configData.tableConfig.columns.length
        "
      >
        <vxe-column
          v-for="(column, index) in configData.tableConfig.columns"
          :key="index"
          :type="column && column.type"
          :field="column && column.field"
          :title="$srv.getI18nBySrv((column && column.title) || '')"
          :width="column && column.width"
        >
          <template
            v-if="column && column.field === 'paintName'"
            #default="{ row }"
          >
            <o-m2o-selector
              v-model="row.paintName"
              :isFunLayout="
                column && column.editor && column.editor.isFunLayout
              "
              :tField="column && column.editor && column.editor.tField"
              :tTable="column && column.editor && column.editor.tTable"
              @on-dochange="m2oChange(row, $event)"
              class="item-v"
            ></o-m2o-selector>
          </template>
        </vxe-column>
      </vxe-table>

      <!-- 展示区域 -->
      <div
        class="display-area"
        v-if="configData.displaySections && configData.displaySections.length"
      >
        <div
          v-for="(section, index) in configData.displaySections"
          :key="index"
          class="display-section"
        >
          <div class="title">
            {{ $srv.getI18nBySrv((section && section.title) || '') }}:
          </div>
          <div class="content">
            {{
              $srv.getI18nBySrv(
                paintInfo[(section && section.dataKey) || ''] || ''
              )
            }}
          </div>
        </div>
      </div>
    </div>
  </o-modal>
</template>

<script lang="ts">
import { VxeTable } from 'vxe-table';
import oModal from '@/components/base/modal/o-modal/index.vue';
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  N_cPaintCodeGuide,
  paintCodeGuideConfig
} from './config';

@T_srv.comp({
  components: {
    oModal
  }
})
export default class cPaintCodeGuide extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({
    type: Object,
    default: () => {}
  })
  config: any;

  /* 组件名 */
  private G_compName: string = 'cPaintCodeGuide';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  /* 弹窗显示控制 */
  private visible: boolean = true;

  /* 表格引用 */
  public $refs!: {
    paintTable: VxeTable;
  };

  /* 零件信息 */
  private partInfo = {
    partNumber: '',
    processRevision: '',
    processModel: '',
    partName: '',
    surfaceType: ''
  };

  /* 配置数据 */
  private configData: N_cPaintCodeGuide.PaintCodeGuideConfig = {
    modalTitle: '',
    partInfoFields: [],
    tableConfig: { columns: [] },
    buttons: [],
    tips: { icon: '', text: '', content: '' },
    displaySections: []
  };

  /* 表格数据 */
  private tableData: N_cPaintCodeGuide.tableData[] = [];

  /* 选中行 */
  private selectedRows: any[] = [];

  /* 喷漆信息 */
  private paintInfo: N_cPaintCodeGuide.paintInfo = {
    paintCode: '',
    paintSequence: ''
  };

  /* 当前层数 */
  private currentLayer: number = 1;

  private rowId: string = '';

  /* 原始数据 */
  // private originalData: N_cPaintCodeGuide.tableData[] = [];

  /* 响应式弹窗尺寸 */
  private get modalSize(): [number, number] {
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;

    // 在小屏幕上使用百分比尺寸，在大屏幕上使用最大限制
    if (screenWidth < 1366) {
      // 笔记本屏幕尺寸
      return [
        Math.min(screenWidth * 0.9, 800),
        Math.min(screenHeight * 0.85, 700)
      ];
    }
    return [800, 720]; // 桌面屏幕使用稍小的高度
  }

  /* 表格动态高度 */
  private get tableHeight(): number {
    const screenHeight = window.innerHeight;
    // 根据屏幕高度动态调整表格高度
    if (screenHeight < 800) {
      return 180; // 小屏幕
    }
    if (screenHeight < 1000) {
      return 220; // 中等屏幕
    }
    return 250; // 大屏幕
  }

  async created() {
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    await this.init();
  }

  mounted() {
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$bus.$emit('compBoxInfo', this.GT_compBoxInfo);
  }

  destroyed() {
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private init() {
    // 初始化零件信息
    const info: N_cPaintCodeGuide.partInfo = this.config?.data?.rows[
      Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD
    ][0];
    if (Tsrv.noValue(info)) {
      return;
    }

    this.rowId = this.config?.data?.rows[
      Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD
    ][0]?.id;

    this.getConfigInfo().then(
      (config: N_cPaintCodeGuide.PaintCodeGuideConfig) => {
        this.configData = config;
        this.configData.partInfoFields.forEach(field => {
          this.partInfo[field.dataKey] = info[field.field];
        });

        // 初始化表格数据
        if (!Tsrv.noValue(info.content)) {
          const content = Tsrv.utils.isJSONString(info.content)
            ? JSON.parse(info.content)
            : info.content;
          this.paintInfo = {
            paintCode: content.paintCode,
            paintSequence: content.paintSequence
          };
          this.tableData = JSON.parse(JSON.stringify(content.sprayPaintData));
          // this.originalData = JSON.parse(JSON.stringify(content.sprayPaintData));

          this.updateCurrentLayer();
        }
      }
    );
  }

  // 获取配置信息
  private getConfigInfo() {
    const gridFunInfo = Tsrv.getFunInfo(
      Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD
    );
    const params = () => {
      return {
        funName: Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD,
        title: 'customFun',
        from: Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD,
        data: {
          rowId: this.rowId
        }
      };
    };

    return new Promise(resolve => {
      Tsrv.doEvent(
        Tsrv.lexicon.globalVar.spName.GetPaintGuideModalConfig,
        gridFunInfo,
        params
      )
        .then(res => {
          if (res.isErr()) {
            this.$msg(res.errmsg);
          } else {
            const returnData = res.getReturnData('conf');
            const data: N_cPaintCodeGuide.PaintCodeGuideConfig =
              returnData.res.data;
            resolve(data);
          }
        })
        .catch(err => {
          this.$msg(err);
        });
    });
  }

  // 更新当前层数
  private updateCurrentLayer() {
    if (this.tableData.length === 0) {
      this.currentLayer = 1;
    } else {
      this.currentLayer = Math.ceil(this.tableData.length / 2) + 1;
    }
  }

  /* 新增喷漆记录 */
  private addPaintRecord() {
    const newRows = [
      {
        index: this.tableData.length + 1,
        surface: `第${this.currentLayer}层正面`,
        paintName: ''
      },
      {
        index: this.tableData.length + 2,
        surface: `第${this.currentLayer}层反面`,
        paintName: ''
      }
    ];
    this.tableData = [...this.tableData, ...newRows];
    this.currentLayer++;
  }

  /* 删除选中行 */
  private deleteSelected() {
    // 获取所有层数
    const allLayers = new Set<number>();
    this.tableData.forEach(row => {
      const layerMatch = row.surface.match(/第(\d+)层/);
      if (layerMatch) {
        allLayers.add(parseInt(layerMatch[1], 10));
      }
    });

    // 过滤掉被删除的行
    const remainingRows = this.tableData.filter(
      row => !this.selectedRows.includes(row)
    );

    // 检查哪些层被完全删除（剩余行中不存在该层的正反面）
    const fullyDeletedLayers = new Set<number>();
    allLayers.forEach(layer => {
      const hasFront = remainingRows.some(
        row => row.surface === `第${layer}层正面`
      );
      const hasBack = remainingRows.some(
        row => row.surface === `第${layer}层反面`
      );
      if (!hasFront && !hasBack) {
        fullyDeletedLayers.add(layer);
      }
    });

    // 重新计算序号和层数
    this.tableData = remainingRows.map((row, index) => {
      // 获取原始层数
      const layerMatch = row.surface.match(/第(\d+)层/);
      if (!layerMatch) return row;

      const originalLayer = parseInt(layerMatch[1], 10);
      // 计算需要减去的层数（完全删除的层数中小于当前层的数量）
      let layersToSubtract = 0;
      fullyDeletedLayers.forEach(layer => {
        if (layer < originalLayer) layersToSubtract++;
      });

      const newLayer = originalLayer - layersToSubtract;
      return {
        ...row,
        index: index + 1,
        surface: row.surface.includes('正面')
          ? `第${newLayer}层正面`
          : `第${newLayer}层反面`
      };
    });

    this.updateCurrentLayer();
    this.selectedRows = [];
  }

  /* 按钮点击处理方法 */
  private handleButtonClick(buttonText: string) {
    switch (buttonText) {
      case 'add_paint_spraying_record':
        this.addPaintRecord();
        break;
      case 'delete':
        this.deleteSelected();
        break;
      case 'save_paint_code':
        this.savePaintCode();
        break;
      default:
        break;
    }
  }

  /* 保存喷漆编码 */
  private savePaintCode() {
    // this.paintSequence =
    //   '喷漆顺序为，底漆 AA只喷正面、底漆BE 只喷反面、面漆 CF颜色为 AD)两面都喷，没有第二种面漆，不保护。';
    // this.paintCode = '1AA 2BE 1CFAD 2HKMN N';

    if (Tsrv.noValue(this.paintInfo.paintCode)) {
      this.$msg('50006, 80, FE, no paintCode');
      return;
    }

    // 如果存在'_XID'，删除'_XID'字段
    const list = this.tableData.map(item => {
      if (!Tsrv.noValue(item['_XID'])) delete item['_XID'];
      return item;
    });

    const content = {
      paintSequence: this.paintInfo.paintSequence,
      paintCode: this.paintInfo.paintCode,
      sprayPaintData: list
    };
    if (!Tsrv.noValue(this.paintInfo.paintCode)) {
      const row: ifs.I_fv[] = [
        {
          field: 'paint_code',
          value: this.paintInfo.paintCode
        } as ifs.I_fv,
        {
          field: 'content',
          value: JSON.stringify(content)
        } as ifs.I_fv
      ];
      const filter = { id: this.rowId };
      this.GT_command.operateData(
        Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD,
        'edit',
        row,
        filter
      ).then(_ => {
        // this.$msg('保存成功');
        // this.originalData = JSON.parse(JSON.stringify(this.tableData));
        this.visible = false;
      });
    }
  }

  /* 表格选中变化事件 */
  private selectChangeEvent({ records }: { records: any[] }) {
    this.selectedRows = records;
  }

  private m2oChange(item, e) {
    item.value = e?.id;
    this.genPaintCode();
  }

  // 生成喷漆编码
  public genPaintCode() {
    // 调用api
    const gridFunInfo = Tsrv.getFunInfo(
      Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD
    );
    // 如果存在'_XID'，删除'_XID'字段
    const list = this.tableData.map(item => {
      if (!Tsrv.noValue(item['_XID'])) delete item['_XID'];
      return item;
    });

    const info = {
      id: this.rowId,
      ...this.partInfo
    };

    const params = () => {
      return {
        funName: Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD,
        title: 'customFun',
        from: Tsrv.lexicon.globalVar.funName.RDPARTITEM_BAT_MOD,
        data: {
          sprayPaintData: list,
          partInfo: info
        }
      };
    };

    Tsrv.doEvent(
      Tsrv.lexicon.globalVar.spName.SetSprayPaintCode,
      gridFunInfo,
      params
    )
      .then(res => {
        if (res.isErr()) {
          this.$msg(res.errmsg);
        } else {
          const returnData = res.getReturnData('conf');
          const data = returnData.res.data;
          this.paintInfo = {
            paintSequence: data.paintSequence,
            paintCode: data.paintCode
          };
        }
      })
      .catch(err => {
        this.$msg(err);
      });
  }

  /* 设置组件整体遮罩 */
  public setMask(p: boolean) {
    this.isMask = p;
  }

  public getMask(p: boolean): boolean {
    return this.isMask;
  }

  // private async handleCancel() {
  //   const originalHash = Tsrv.utils.md5(JSON.stringify(this.originalData));
  //   const currentHash = Tsrv.utils.md5(JSON.stringify(this.tableData));

  //   if (originalHash !== currentHash) {
  //     this.$Modal.confirm({
  //       title: Tsrv.getI18nByValue('提示'),
  //       content: Tsrv.getI18nByValue('未保存，确认是否关闭？'),
  //       onOk: () => {
  //         this.visible = false;
  //       },
  //       onCancel: () => {
  //         // 不关闭弹窗
  //       }
  //     });
  //   } else {
  //     this.visible = false;
  //   }
  // }
}
</script>

<style lang="scss" scoped>
.paint-guide-container {
  padding: 14px 14px 0 14px;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  max-height: calc(100vh - 100px);

  /* 确保内容区域有足够的弹性空间 */
  > *:not(.vxe-table) {
    flex-shrink: 0;
  }

  .vxe-table {
    flex: 1 1 auto;
    min-height: 120px;
    max-height: 300px;
  }

  .part-info {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 14px;
    gap: 10px;

    .info-item {
      min-width: 45%;
      flex: 1;

      .label {
        font-weight: bold;
        margin-right: 8px;
        color: #666;
      }

      .value {
        color: #333;
      }
    }

    @media (max-width: 768px) {
      .info-item {
        min-width: 100%;
      }
    }
  }

  .action-buttons {
    margin: 12px 0;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;

    @media (max-width: 480px) {
      flex-direction: column;
      gap: 6px;
    }
  }

  .tips {
    margin: 12px 0;
    padding: 8px 12px;
    background-color: #f0f9ff;
    border: 1px solid #91d5ff;
    border-radius: 4px;
    color: #1890ff;
    font-size: 12px;

    .ivu-icon {
      margin-right: 4px;
    }
  }

  .display-area {
    border: 1px solid #e8e8e8;
    padding: 12px 12px 0 12px;
    border-radius: 4px;
    background-color: #fafafa;
    flex-shrink: 0;
    min-height: 90px;

    .display-section {
      margin-bottom: 12px;

      .title {
        font-weight: bold;
        margin-bottom: 6px;
        color: #333;
        font-size: 13px;
      }

      .content {
        background: #f5f5f5;
        padding: 10px;
        border-radius: 4px;
        min-height: 36px;
        word-break: break-all;
        font-family: monospace;
        font-size: 12px;
        line-height: 1.4;
        max-height: 90px;
        overflow-y: auto;
      }
    }
  }

  // 响应式调整
  @media (max-width: 1366px) {
    padding: 12px;

    .part-info {
      margin-bottom: 12px;

      .info-item {
        min-width: 100%;
      }
    }

    .action-buttons {
      margin: 8px 0;
    }

    .display-area {
      padding: 10px;
      min-height: 100px;

      .display-section {
        margin-bottom: 10px;

        .content {
          padding: 8px;
          min-height: 35px;
          font-size: 11px;
          max-height: 80px;
        }
      }
    }
  }

  @media (max-width: 768px) {
    padding: 8px;

    .part-info {
      gap: 8px;
    }

    .tips {
      font-size: 11px;
      padding: 6px 8px;
    }

    .display-area {
      padding: 8px;
      min-height: 90px;

      .content {
        max-height: 60px;
        font-size: 10px;
      }
    }
  }

  @media (max-width: 480px) {
    .display-area {
      min-height: 80px;

      .content {
        max-height: 50px;
      }
    }
  }
}
/* 覆盖footer高度 */
::v-deep .footer {
  height: 20px !important;
  min-height: 20px;
  padding: 0;

  .footer-btn {
    display: none;
  }
}
</style>
